package com.hwn.datax.service.impl;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hwn.datax.domain.ServerInfo;
import com.hwn.datax.service.ConfigService;
import com.hwn.datax.service.ServerInfoService;
import com.hwn.datax.utils.JschUtil;
import com.jcraft.jsch.JSchException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Administrator
 * @description 针对表【monitor_server_info(服务器监控表)】的数据库操作Service实现
 * @createDate 2023-04-17 21:45:39
 */
@Service
public class ServerInfoServiceImpl implements ServerInfoService, DisposableBean {

    private final Map<Integer, ServerInfo> serverInfoMap = new HashMap<>();

    private final static String CONFIG_KEY = "ServerInfo";
    ConfigService configService;

    @Autowired
    public ServerInfoServiceImpl(ConfigService configService) {
        this.configService = configService;
        JSONObject config = configService.getConfig(CONFIG_KEY);
        if (config != null) {
            config.forEach((k, v) -> {
                serverInfoMap.put(Integer.valueOf(k), JSONUtil.toBean((JSONObject) v, ServerInfo.class));
            });
        }
    }

    @Override
    public ServerInfo getById(Integer id) {
        return serverInfoMap.get(id);
    }

    @Override
    public List<ServerInfo> list(){
        return List.copyOf(serverInfoMap.values());
    }


    @Override
    public void save(ServerInfo serverInfo) {
        if (serverInfo.getId() == null) {
            serverInfo.setId(serverInfoMap.size() + 1);
        }
        serverInfoMap.put(serverInfo.getId(), serverInfo);
        configService.saveConfig(CONFIG_KEY, JSONUtil.toJsonStr(serverInfoMap));
    }


    /**
     * 测试服务器连接
     *
     * @param serverInfo
     */
    @Override
    public void testConnection(ServerInfo serverInfo) {
        try {
            JschUtil.getSession(serverInfo);
        } catch (JSchException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void destroy() throws Exception {
        JschUtil.closeSessions();
    }
}




